package com.nali.dal.statement.function.formatter.date;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Component;

import com.nali.dal.statement.function.AbstractDataHandler;
import com.nali.dal.statement.function.FunctionArgument;
import com.nali.dal.statement.function.FunctionException;

/**
 * cpp的奇怪日期，yyyyMMdd可以没有年月日中的任何一个
 * @author sam Created on 2011-4-15
 */
@Component
public class CppDate extends AbstractDataHandler<Date> {

	@Override
	public Date handle(List<Object> argList) throws FunctionException {
		Object arg1 = argList.get(0);
		int val;
		if (arg1 instanceof Number) {
			Number num = (Number) arg1;
			val = num.intValue();
		} else if (arg1 instanceof String) {
			String str = (String) arg1;
			val = Integer.parseInt(str);
		} else {
			throw new FunctionException("illeal argument type:" + arg1);
		}
		int date=Math.max(val%100, 1);
		val/=100;
		int month=Math.max(val%100, 1);
		val/=100;
		int year=val;
		if(year==0) {
			return null;
		}
		Calendar cal = Calendar.getInstance();
		cal.set(year, month, date, 0, 0, 0);
		cal.set(Calendar.MILLISECOND, 0);
		return cal.getTime();
	}

	@Override
	public void validate(List<FunctionArgument> arguments) throws FunctionException {
		checkSize(arguments, 1, 1);
	}
}
